package com.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.constant.ProductConstant;
import com.common.to.SkuReductionTo;
import com.common.to.SpuBoundTo;
import com.common.to.UpSkuTo;
import com.common.to.WareSkuTo;
import com.common.utils.PageUtils;
import com.common.utils.Query;
import com.common.utils.R;
import com.gulimall.product.dao.AttrDao;
import com.gulimall.product.dao.SkuInfoDao;
import com.gulimall.product.dao.SpuInfoDao;
import com.gulimall.product.dao.SpuInfoDescDao;
import com.gulimall.product.entity.*;
import com.gulimall.product.feign.CouponFeignService;
import com.gulimall.product.feign.EsSkuFeignService;
import com.gulimall.product.feign.WareSkuFeignService;
import com.gulimall.product.service.*;
import com.gulimall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDao spuInfoDao;
    @Autowired
    SpuInfoDescDao spuInfoDescDao;
    @Autowired
    SpuImagesService spuImagesService;
    @Autowired
    AttrDao attrDao;
    @Autowired
    ProductAttrValueService productAttrValueService;
    @Autowired
    SkuInfoDao skuInfoDao;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    BrandService brandService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    AttrService attrService;
    @Autowired
    WareSkuFeignService wareSkuFeignService;
    @Autowired
    EsSkuFeignService esSkuFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper=new QueryWrapper<>();
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and(query->{
                query.eq("id",key).or().like("spu_name",key);
            });
        }

        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)&&!"0".equalsIgnoreCase(status)){
            queryWrapper.eq("publish_status",status);
        }

        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId)&&!"0".equalsIgnoreCase(brandId)){
            queryWrapper.eq("brand_id",brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId)&&!"0".equalsIgnoreCase(catelogId)){
            queryWrapper.eq("catalog_id",catelogId);
        }
        /**
         * status: 0
         * key: 1
         * brandId: 9
         * catelogId: 225
         */

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1、保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity=new SpuInfoEntity();
        BeanUtils.copyProperties(vo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        spuInfoDao.insert(spuInfoEntity);

        //2、保存Spu的描述图片 pms_spu_info_desc
        SpuInfoDescEntity spuInfoDescEntity=new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",",vo.getDecript()));
        spuInfoDescDao.insert(spuInfoDescEntity);



        //3、保存spu的图片集 pms_spu_images
        List<String> list=vo.getImages();
        spuImagesService.saveList(spuInfoEntity.getId(),list);

        //4、保存spu的规格参数;pms_product_attr_value
        List<BaseAttrs> baseAttrsList = vo.getBaseAttrs();
        List<ProductAttrValueEntity> productList = baseAttrsList.stream().map(baseAttrs -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setAttrId(baseAttrs.getAttrId());
            productAttrValueEntity.setAttrName(attrDao.selectById(baseAttrs.getAttrId()).getAttrName());
            productAttrValueEntity.setAttrValue(baseAttrs.getAttrValues());
            productAttrValueEntity.setQuickShow(baseAttrs.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productList);


        //5、保存spu的积分信息；gulimall_sms->sms_spu_bounds
        SpuBoundTo spuBoundTo=new SpuBoundTo();
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        Bounds bounds = vo.getBounds();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        R r1 = couponFeignService.saveSpuBounds(spuBoundTo);
        if(r1.getCode()!=0){
            log.error("保存积分信息失败");
        }


        //5、保存当前spu对应的所有sku信息；
        List<Skus> skus = vo.getSkus();
        if(skus!=null&&skus.size()>0) {
            skus.forEach(sku -> {
                List<Images> imagesList = sku.getImages();
                String defaultImage="";
                for (Images images : imagesList) {
                    if(images.getDefaultImg()==1){
                        defaultImage=images.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity=new SkuInfoEntity();
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                BeanUtils.copyProperties(sku,skuInfoEntity);
                skuInfoEntity.setCatalogId(vo.getCatalogId());
                skuInfoEntity.setBrandId(vo.getBrandId());
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                skuInfoEntity.setSaleCount(0L);
                //5.1）、sku的基本信息；pms_sku_info
                skuInfoDao.insert(skuInfoEntity);

                List<SkuImagesEntity> skuImagesEntityList = sku.getImages().stream().map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setImgUrl(image.getImgUrl());
                    skuImagesEntity.setDefaultImg(image.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                //5.2）、sku的图片信息；pms_sku_image
                skuImagesService.saveBatch(skuImagesEntityList);

                List<Attr> attrList = sku.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntityList = attrList.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setAttrSort(0);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                //5.3）、sku的销售属性信息：pms_sku_sale_attr_value
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntityList);

                SkuReductionTo skuReductionTo=new SkuReductionTo();
                BeanUtils.copyProperties(sku,skuReductionTo);
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                // //5.4）、sku的优惠、满减等信息；gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
                if(skuReductionTo.getReducePrice().compareTo(new BigDecimal(0))==1||skuReductionTo.getFullCount()>0) {
                    R r = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r.getCode() != 0) {
                        log.error("远程保存sku优惠、满减信息失败");
                    }
                }
            });

        }



    }

    //TODO 上传sku商品
    @Override
    public void upSku(Long spuId) {
        List<SkuInfoEntity> skuInfoEntityList = skuInfoDao.selectList(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));

        //找出所有对应的skuId,转换为map结构
        List<Long> skuIdList = skuInfoEntityList.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());


        Map<Long, Boolean> skuMap = null;
        try {
            List<WareSkuTo> wareSkuToList = wareSkuFeignService.check(skuIdList);
            skuMap = wareSkuToList.stream().collect(Collectors.toMap(WareSkuTo::getSkuId, item -> item.isEnough()));
        } catch (Exception e) {
            log.error("库存服务发生异常：原因：｛｝",e);
        }

        Map<Long, Boolean> finalSkuMap = skuMap;
        List<UpSkuTo> upSkuToList = skuInfoEntityList.stream().map(skuInfoEntity -> {
            //skuPrice,skuImg,
            // hasStock,hasScore
            // ,brandName，brandImg，catalogName， @Data
            //    public static class Attrs{
            //        private Long attrId;
            //        private String attrName;
            //        private String attrValue;
            //    }
            UpSkuTo upSkuTo = new UpSkuTo();
            BeanUtils.copyProperties(skuInfoEntity, upSkuTo);
            upSkuTo.setSkuPrice(skuInfoEntity.getPrice());
            upSkuTo.setSkuImg(skuInfoEntity.getSkuDefaultImg());
            //查出对应的品牌对象
            BrandEntity brandEntity = brandService.getById(skuInfoEntity.getBrandId());
            upSkuTo.setBrandName(brandEntity.getName());
            upSkuTo.setBrandImg(brandEntity.getLogo());
            //查出对应的分类对象
            CategoryEntity categoryEntity = categoryService.getById(skuInfoEntity.getCatalogId());
            upSkuTo.setCatalogName(categoryEntity.getName());

            //找出是检索属性的属性
            List<UpSkuTo.Attrs> attrsList = productAttrValueService.getEsAttr(spuId);
            upSkuTo.setAttrs(attrsList);

            //设置另外两个属性
            upSkuTo.setHotScore(0L);
            if (finalSkuMap == null) {
                upSkuTo.setHasStock(true);
            } else {
                upSkuTo.setHasStock(finalSkuMap.get(skuInfoEntity.getSkuId()));
            }

            return upSkuTo;

        }).collect(Collectors.toList());

        //调用ES模块将相关的数据保存到ES中
        R r = null;
        try {
            r = esSkuFeignService.saveEs(upSkuToList);
        } catch (Exception e) {
            log.error("++++++++++++++++++"+e);
        }
        if(r.getCode()==0){
            //修改当前sku状态
            spuInfoDao.changeStatus(spuId,ProductConstant.SPU_STATUS.SPU_UP.getCode());
        }else{
            //TODO SKU远程调用es模块保存失败，重复调用？重试？
        }

    }


}